import { ApiCall } from 'tsrpc'
import { ReqValidateConfigs, ResValidateConfigs } from '../shared/api_config_editor/PtlValidateConfigs'
import { ValidationResult } from '../shared/api_config_editor/base'
import { configManager } from '../config/ConfigManager'

export default async function (call: ApiCall<ReqValidateConfigs, ResValidateConfigs>) {
    try {
        const { type, configs } = call.req
        
        if (type) {
            // 验证特定类型的配置
            let configsToValidate = configs
            
            if (!configsToValidate) {
                // 如果没有提供配置数据，从现有配置中获取
                switch (type) {
                    case 'equipment':
                        configsToValidate = configManager.getAllEquipmentTemplates()
                        break
                    case 'skill':
                        // 需要实现getAllSkills方法
                        configsToValidate = []
                        break
                    default:
                        // 从文件中读取
                        const fs = require('fs')
                        const path = require('path')
                        const configDir = path.resolve(__dirname, '../core/config')
                        const files = fs.readdirSync(configDir)
                        const matchingFile = files.find((file: string) => 
                            file.startsWith(type + '_') && file.endsWith('.json')
                        )
                        
                        if (matchingFile) {
                            const filePath = path.join(configDir, matchingFile)
                            const content = fs.readFileSync(filePath, 'utf-8')
                            const jsonData = JSON.parse(content)
                            configsToValidate = Array.isArray(jsonData) ? jsonData : [jsonData]
                        } else {
                            configsToValidate = []
                        }
                }
            }
            
            // 执行验证
            const result = validateConfigType(type, configsToValidate)
            
            call.succ({
                data: result
            })
            
        } else {
            // 验证所有配置类型
            const results: Record<string, ValidationResult> = {}
            
            // 验证装备配置
            const equipments = configManager.getAllEquipmentTemplates()
            results.equipment = validateConfigType('equipment', equipments)
            
            // 验证技能配置
            // 需要实现getAllSkills方法
            results.skill = validateConfigType('skill', [])
            
            // 验证其他配置文件
            const fs = require('fs')
            const path = require('path')
            const configDir = path.resolve(__dirname, '../core/config')
            
            if (fs.existsSync(configDir)) {
                const files = fs.readdirSync(configDir)
                const jsonFiles = files.filter((file: string) => file.endsWith('.json'))
                
                for (const file of jsonFiles) {
                    const fileName = file.replace('.json', '')
                    const parts = fileName.split('_')
                    
                    if (parts.length >= 2) {
                        const configType = parts[0]
                        
                        if (!results[configType]) {
                            try {
                                const filePath = path.join(configDir, file)
                                const content = fs.readFileSync(filePath, 'utf-8')
                                const data = JSON.parse(content)
                                const configArray = Array.isArray(data) ? data : [data]
                                
                                results[configType] = validateConfigType(configType, configArray)
                            } catch (error) {
                                results[configType] = {
                                    isValid: false,
                                    errors: [{
                                        id: file,
                                        message: `读取配置文件失败: ${(error as any).message}`,
                                        severity: 'error'
                                    }],
                                    warnings: [],
                                    validatedCount: 0
                                }
                            }
                        }
                    }
                }
            }
            
            call.succ({
                data: results
            })
        }
        
    } catch (error) {
        console.error('Failed to validate configs:', error)
        call.error('配置验证失败', {
            errors: [(error as any).message]
        })
    }
}

/**
 * 验证特定类型的配置
 */
function validateConfigType(type: string, configs: any[]): ValidationResult {
    const errors: any[] = []
    const warnings: any[] = []
    
    switch (type) {
        case 'equipment':
            for (const config of configs) {
                // 验证装备配置
                if (!config.id) {
                    errors.push({
                        id: config.name || 'unknown',
                        field: 'id',
                        message: '装备ID不能为空',
                        severity: 'error'
                    })
                }
                
                if (!config.name) {
                    errors.push({
                        id: config.id || 'unknown',
                        field: 'name',
                        message: '装备名称不能为空',
                        severity: 'error'
                    })
                }
                
                if (config.quality) {
                    if (config.quality.min > config.quality.max) {
                        errors.push({
                            id: config.id || config.name || 'unknown',
                            field: 'quality',
                            message: '品质最小值不能大于最大值',
                            severity: 'error'
                        })
                    }
                }
                
                // 验证基础属性
                if (config.baseAttributes && Array.isArray(config.baseAttributes)) {
                    for (const attr of config.baseAttributes) {
                        if (attr.min > attr.max) {
                            warnings.push({
                                id: config.id || config.name || 'unknown',
                                field: `baseAttributes.${attr.key}`,
                                message: `属性${attr.key}的最小值大于最大值`,
                                severity: 'warning'
                            })
                        }
                    }
                }
            }
            break
            
        case 'skill':
            for (const config of configs) {
                // 验证技能配置
                if (!config.skillId && !config.id) {
                    errors.push({
                        id: config.name || 'unknown',
                        field: 'skillId',
                        message: '技能ID不能为空',
                        severity: 'error'
                    })
                }
                
                if (!config.name) {
                    errors.push({
                        id: config.skillId || config.id || 'unknown',
                        field: 'name',
                        message: '技能名称不能为空',
                        severity: 'error'
                    })
                }
                
                if (config.maxLevel && config.maxLevel < 1) {
                    errors.push({
                        id: config.skillId || config.id || config.name || 'unknown',
                        field: 'maxLevel',
                        message: '技能最高等级必须大于0',
                        severity: 'error'
                    })
                }
            }
            break
            
        default:
            // 基础验证
            for (const config of configs) {
                if (!config.id && !config.name) {
                    errors.push({
                        id: 'unknown',
                        message: '配置必须包含id或name字段',
                        severity: 'error'
                    })
                }
            }
    }
    
    return {
        isValid: errors.length === 0,
        errors,
        warnings,
        validatedCount: configs.length
    }
}
